package com.atguigu.gulimail.Service.impl;

import com.atguigu.gulimail.Enum.PayEnum;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Stream;

/**
 * @author Guo 2022/9/7 10:19:41
 */
@Service("queryGrantTypeService")
public class QueryGrantTypeService {

    private static String MSG = "使用 %s ,消费了 %s 元";

    @Resource
    private GrantTypeService grantTypeService;

    private Map<String, Function<String, String>> grantTypeMap = new HashMap<>();

    /**
     * 初始化业务分派逻辑,代替了if-else部分
     * key: 支付渠道
     * value: lambda表达式,最终会获得该支付的方式
     */
    @PostConstruct
    public void dispatcherInit() {
        grantTypeMap.put(PayEnum.ALI_PAY.getChannel(), channel -> grantTypeService.aliPay(channel));
        grantTypeMap.put(PayEnum.WECHAT_PAY.getChannel(), channel -> grantTypeService.wechatPay(channel));
        grantTypeMap.put(PayEnum.XIAO_MI_PAY.getChannel(), channel -> grantTypeService.xiaomiPay(channel));
        // 显式重写
        grantTypeMap.put(PayEnum.HUA_WEI_PAY.getChannel(), new Function<String, String>() {
            @Override
            public String apply(String s) {
                return grantTypeService.xiaomiPay(s);
            }
        });
    }

    public String getResult(String channel,String amount) {
        //Controller根据 支付渠道channel 去查询 发放方式grantType
        Function<String, String> result = grantTypeMap.get(channel);
        if (result != null) {
            //传入channel 执行这段表达式获得String型的grantType
            // 这里的apply()指的是：利用lambda隐式/直接重写的Function接口中的apply()方法，真正执行的是return grantTypeService.aliPay(channel));
            return String.format(MSG,result.apply(channel),amount);
        }
        return "输入渠道码有误";
    }


}
